<?php

class DefaultController extends BackendController
{
	public function actionIndex()
	{
		$this->render('index');
	}
    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(array('/backend/login'));
    }

    public function actionDeleteImage() {
        if (Yii::app()->request->isPostRequest):
            $imageName = Yii::app()->request->getPost('imageName');
            $model = Yii::app()->request->getPost('model');
            $image = Yii::app()->request->getPost('colImage') ? Yii::app()->request->getPost('colImage') : 'image';
            if ($imageName):
                $params = array(
                    'imageName'   => $imageName,
                    'id'          => Yii::app()->request->getPost('imageID'),
                    'model'       => $model,
                    'colFileName' => $image,
                    'folder'      => 'uploads/' . strtolower($model)
                );
                self::deleteImage($params);
                echo CJSON::encode("Image was deleted");
                Yii::app()->end();
            endif;
        endif;
    }

    protected function deleteImage($params) {
        $data = $params['model']::model()->find('id=:id', array(':id' => $params['id']));
        if ($data) {
            $fileName = isset($params['colFileName']) ? $params['colFileName'] : 'image';
            $typeFile = explode(',', $data[$fileName]);
            if (in_array($params['imageName'], $typeFile)) {
                $diffTypeFile = array_diff($typeFile, array($params['imageName']));
                $typeFile     = implode(',', $diffTypeFile);
                $params['model']::model()->updateByPk($params['id'], array($params['colFileName'] => $typeFile));
                unlink($params['folder'] . '/' . $params['imageName']);
            } else {
                foreach ($typeFile as $file) {
                    if (!empty($file)) {
                        unlink($params['folder'] . '/' . $file);
                    }
                }
            }
        }
    }

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}